package com.example.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.java.entity.RequestData;
import com.example.java.entity.User;
import com.example.java.interceptor.ThreadLocalHolder;
import com.example.java.mapper.UserMapper;
import com.example.java.security.JwtTokenUtil;
import com.example.java.service.impl.UserService;
import com.example.java.utils.JsonUtils;
import com.example.java.utils.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class UserController {

    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${wx.AppID}")
    private String Appid;

    @Value("${wx.AppSecret}")
    private String AppSecret;


    @RequestMapping(value = "/check_login", method = RequestMethod.POST)
    public Result login_token(@RequestBody RequestData requestData) {
        String code = requestData.getCode();
        // 通过code 查询出来  openId
        String wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Appid + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
        // 使用 RestTemplate 发送请求
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(wxLoginUrl, String.class);
        User user = new User();
        try {
            // 通过openId 查询出来是否存在的数据放入缓存中，并且带有token的
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(result);
            String openid = jsonNode.get("openid").asText();
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("openid", openid);
            user = userMapper.selectOne(queryWrapper);

//            String access_token = get_access_token();
//            sendMessage(access_token, openid);

            if (user != null) {
                String token = jwtTokenUtil.generateToken(String.valueOf(user.getId()));
                user.setToken(token);
                user.setOpenId("");
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return Result.ok().data("data", user);
    }

    /**
     * 推送消息
     *
     * @param token
     * @param openid 1、需要发送消息内容
     *               2、小程序token
     *               3、小程序openId
     *               4、小程序发送模板ID template_id
     */
    public Map<String, Object> sendMessage(String token, String openid) {
        String wxUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构建请求体的Map
        Map<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("touser", openid);
        requestBodyMap.put("template_id", "Mc8HbUrM5o3Pl4c0mwCA8tsbnuCjvww9yht7nbDCtWw");
        requestBodyMap.put("page", "pages/index/index");

        // 构建data部分
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("date6", Collections.singletonMap("value", "2022-06-04 20:33:44"));
        dataMap.put("phrase2", Collections.singletonMap("value", "通过"));
        dataMap.put("thing49", Collections.singletonMap("value", "请求审批"));

        requestBodyMap.put("data", dataMap);

        // 使用Jackson将Map转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String requestBody = null;  // 初始化为null

        try {
            requestBody = objectMapper.writeValueAsString(requestBodyMap);
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
            ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error while creating JSON request body");
        }

        Map<String, Object> result = new HashMap<>();
        // 如果请求体初始化成功，才继续后续操作
        if (requestBody != null) {
            // 构建请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
            // 拼接URL
            String url = wxUrl;
            // 发送POST请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> re = restTemplate.postForEntity(url, requestEntity, String.class);
            String aaa = re.getBody();
            try {
                JsonNode jsonNode = objectMapper.readTree(aaa);
                System.out.println(jsonNode);
                result.put("errcode", jsonNode.get("errcode").asInt());
                result.put("errmsg", jsonNode.get("errmsg").asText());
            } catch (Exception e) {
                e.printStackTrace();
            }


            System.out.println(aaa);
            System.out.println("==================");
        }
        return result;
    }

    @RequestMapping(value = "/pushmessage", method = RequestMethod.POST)
    public Result pushMessage(HttpServletRequest request) {
        String authorizationHeader = request.getHeader("token");
        String userId = jwtTokenUtil.parseToken(authorizationHeader);
        Boolean b = true;
        Map<String, Object> res = new HashMap<>();
        if (userId != null) {
            Long id = Long.parseLong(userId);
            User user = userMapper.selectById(id);
            if (user != null) {
                String openId = user.getOpenId();
                String access_token = get_access_token();
                res = sendMessage(access_token, openId);
                System.out.println(res);
            } else {
                b = false;
                return Result.error().message("无法查询到用户相关信息!");
            }
        } else {
            b = false;
            return Result.error().message("请登录!");
        }
        return Result.ok().data("data", res);
    }

    public String get_access_token() {
        String wxTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Appid + "&secret=" + AppSecret;
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(wxTokenUrl, String.class);
        String access_token = "";
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(result);
            access_token = jsonNode.get("access_token").asText();

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        return access_token;

    }

    @RequestMapping(value = "/userByToken", method = RequestMethod.POST)
    public Result getUserInfoByToken() {
        String token = ThreadLocalHolder.getAuthorizationHeader();
        ThreadLocalHolder.clear();
        User user = new User();
        user = null;
        if (token != "") {
            String info = jwtTokenUtil.parseToken(token);
            user = userMapper.selectById(info);
        }

        return Result.ok().data("data", user);
    }


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result getToken(@RequestBody RequestData requestData) {

        String code = requestData.getCode();
        User user = new User();
        try {
            // 获取 openid session_key
            String wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Appid + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
            // 使用 RestTemplate 发送请求
            RestTemplate restTemplate = new RestTemplate();
            String result = restTemplate.getForObject(wxLoginUrl, String.class);

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(result);
            String sessionKey = jsonNode.get("session_key").asText();
            // 通过这个OPEN ID 查询出来用户信息
            if (requestData.getEncryptedData() != null && requestData.getIv() != null) {

                String res = JsonUtils.decryptUserInfo(sessionKey, requestData.getIv(), requestData.getEncryptedData());
                JsonNode json = JsonUtils.parseJson(res);
                user.setAvatarUrl(json.get("avatarUrl").asText());
                user.setCity(json.get("city").asText());
                user.setCountry(json.get("country").asText());
                user.setGender(Integer.parseInt(json.get("gender").asText()));
                user.setLanguage(json.get("language").asText());
                user.setNickName(json.get("nickName").asText());
                user.setOpenId(json.get("openId").asText());
                user.setProvince(json.get("province").asText());

                String openid = jsonNode.get("openid").asText();
                User userInfo = userMapper.selectByOpenId(openid);

                if (userInfo != null && userInfo.getId() != null) {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("openId", openid);
                    userMapper.update(user, queryWrapper);
                } else {
                    // 插入数据
                    userMapper.insert(user);
                }
                String token = jwtTokenUtil.generateToken(String.valueOf(userInfo.getId()));
                user.setToken(token);
            } else {
                user = null;
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return Result.ok().data("data", user).message("退出成功!");
    }


}
